<template>
  <view class="patrol-container">
    <!-- 顶部tab -->
    <view class="patrol-tabs">
      <view :class="['tab', activeTab === 0 ? 'active' : '']" @click="switchTab(0)">
        当前任务<text v-if="currentCount > 0" class="tab-badge">{{ currentCount }}</text>
      </view>
      <view :class="['tab', activeTab === 1 ? 'active' : '']" @click="switchTab(1)">
        历史任务<text v-if="historyCount > 0" class="tab-badge">{{ historyCount }}</text>
      </view>
    </view>
    <!-- 任务列表 -->
    <view v-for="item in taskList" :key="item.taskId" class="task-card">
      <view class="task-header">
        <view class="task-title">{{ item.planName }}</view>
        <view class="task-status" :class="item.statusClass">{{ item.statusText }}</view>
      </view>
      <!-- 分割线 -->
      <view class="task-divider"></view>
      <view class="task-info">
        <view>小区：{{ item.communityName }}</view>
        <view>日期：{{ item.taskDate }}</view>
        <view>
          时间：{{ formatTime(item.plannedStartTime) }} 至 {{ formatTime(item.plannedEndTime) }}
        </view>
        <view>备注：{{ item.remark ? item.remark : '无' }}</view>
      </view>
      <view class="task-action-row">
        <button
          v-if="item.taskStatus === 0"
          class="start-btn btn-blue"
          @click="goToDetail(item)"
        >开始巡更</button>
        <button
          v-else-if="item.taskStatus === 1"
          class="start-btn btn-green"
          @click="goToDetail(item)"
        >继续巡更</button>
        <button
          v-else-if="item.taskStatus === 3"
          class="start-btn btn-yellow"
          @click="goToDetail(item)"
        >重启巡更</button>
      </view>
    </view>
    <view v-if="taskList.length === 0" class="empty-tip">暂无任务</view>
  </view>
</template>

<script>
import request from '@/util/request.js'
export default {
  name: 'PatrolIndex',
  data() {
    return {
      activeTab: 0,
      todayCount: 2,
      historyCount: 2,
      taskList: [],
      mockTodayList: [],
      allTaskList: [],
      currentCount: 0,
      historyCount: 0,
      currentCommunityId: ''
    }
  },
  methods: {
    switchTab(tab) {
      this.activeTab = tab;
      this.filterTaskList();
    },
    filterTaskList() {
      if (this.activeTab === 0) {
        // 当前任务：0未开始，1进行中，3已暂停
        this.taskList = this.allTaskList.filter(item => [0, 1, 3].includes(item.taskStatus));
        this.currentCount = this.taskList.length;
      } else {
        // 历史任务：2已完成，4已取消，5执行失败
        this.taskList = this.allTaskList.filter(item => [2, 4, 5].includes(item.taskStatus));
        this.historyCount = this.taskList.length;
      }
    },
    formatTime(dateTimeStr) {
      if (!dateTimeStr) return '';
      // 检查是否是英文格式时间，比如 "Sat Jun 21 17:03:18 CST 2025"
      if (dateTimeStr.includes('CST') || dateTimeStr.includes('GMT')) {
        try {
          const date = new Date(dateTimeStr);
          if (!isNaN(date.getTime())) {
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            return `${hours}:${minutes}`;
          }
        } catch (e) {
          console.error('时间格式化错误:', e);
        }
      }
      
      // 如果是标准格式，如 "2023-06-21 17:03:18"
      const time = dateTimeStr.split(' ')[1];
      return time ? time.slice(0, 5) : '';
    },
    setMockList() {
      // 合并所有mock数据
      this.allTaskList = [...this.mockTodayList, ...this.mockHistoryList];
      this.filterTaskList();
    },
    async getAllTaskList() {
      // 从Storage获取小区ID
      const communityId = uni.getStorageSync('currentCommunityId') || 0;
      console.log('获取巡更任务列表，当前小区ID:', communityId);
      
      // 将communityId作为对象参数传递给后端
      const res = await request({ 
        url: 'patrol-server/patrolTask/planList', 
        method: 'POST',
        data: communityId
      });
      
      const statusMap = {
        0: { status: '待开始', statusText: '待开始', statusClass: 'status-todo', showBtn: true },
        1: { status: '进行中', statusText: '进行中', statusClass: 'status-doing', showBtn: true },
        2: { status: '已完成', statusText: '已完成', statusClass: 'status-done', showBtn: false },
        3: { status: '已暂停', statusText: '已暂停', statusClass: 'status-paused', showBtn: true },
        4: { status: '已取消', statusText: '已取消', statusClass: 'status-done', showBtn: false },
        5: { status: '执行失败', statusText: '执行失败', statusClass: 'status-failed', showBtn: false }
      };
      
      this.allTaskList = (res.data || []).map(item => {
        const statusInfo = statusMap[item.taskStatus] || {};
        return {
          ...item,
          ...statusInfo
        };
      });
      
      this.filterTaskList();
    },
    // 加载任务列表（提供给其他页面调用的方法）
    loadTasks() {
      this.getAllTaskList();
    },
    goToDetail(item) {
      uni.navigateTo({
        url: `/pages/patrol/detail?taskId=${item.taskId}`
      });
    }
  },
  mounted() {
    this.getAllTaskList();
  },
  onShow() {
    // 从全局变量或本地存储获取小区ID
    const app = getApp();
    let communityId = 0;
    
    if (app.globalData && app.globalData.currentCommunityId) {
      communityId = app.globalData.currentCommunityId;
    } else {
      // 备用方案：从本地存储获取
      const communityObj = uni.getStorageSync('currentCommunityObj');
      communityId = communityObj ? communityObj.id : 0;
    }
    
    this.currentCommunityId = communityId;
    console.log('巡更页面显示，小区ID:', this.currentCommunityId);
    
    // 每次页面显示时刷新数据
    this.getAllTaskList();
  }
}
</script>

<style scoped>
.patrol-container {
  background: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 120rpx;
}
.patrol-tabs {
  display: flex;
  background: #fff;
  border-radius: 16rpx;
  margin: 24rpx 24rpx 0 24rpx;
  box-shadow: 0 2rpx 8rpx #e6e6e6;
  overflow: hidden;
}
.tab {
  flex: 1;
  text-align: center;
  padding: 28rpx 0;
  font-size: 30rpx;
  color: #888;
  position: relative;
  font-weight: 500;
}
.tab.active {
  color: #1a7cf7;
  border-bottom: 4rpx solid #1a7cf7;
  background: #f7faff;
}
.tab-badge {
  background: #ff9800;
  color: #fff;
  border-radius: 20rpx;
  font-size: 22rpx;
  padding: 2rpx 10rpx;
  margin-left: 8rpx;
}
.task-card {
  position: relative;
  background: #fff;
  border-radius: 16rpx;
  margin: 24rpx 24rpx 0 24rpx;
  box-shadow: 0 2rpx 8rpx #e6e6e6;
  padding: 36rpx 28rpx 28rpx 28rpx;
  min-height: 180rpx;
}
.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}
.task-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #222;
  margin-bottom: 8rpx;
}
.task-status {
  font-size: 24rpx;
  border-radius: 20rpx;
  padding: 4rpx 18rpx;
  font-weight: 500;
}
.status-todo {
  color: #1a7cf7;
  background: #eaf4ff;
}
.status-doing {
  color: #4caf50;
  background: #e8f5e9;
}
.status-paused {
  color: #ff9800;
  background: #fff3e0;
}
.status-done {
  color: #888;
  background: #f0f0f0;
}
.status-failed {
  color: #f44336;
  background: #ffebee;
}
.task-info {
  font-size: 30rpx;
  color: #444;
  margin-bottom: 20rpx;
  text-align: left;
  line-height: 2.2;
  letter-spacing: 1rpx;
}
.task-action-row {
  display: flex;
  justify-content: flex-end;
  margin-top: 12rpx;
}
.start-btn {
  border-radius: 20rpx;
  font-size: 24rpx;
  padding: 8rpx 24rpx;
  border: none;
  min-width: 100rpx;
  min-height: 40rpx;
  box-shadow: none;
  position: absolute;
  right: 28rpx;
  bottom: 28rpx;
}
.btn-blue {
  background: #1a7cf7;
  color: #fff;
}
.btn-green {
  background: #4caf50;
  color: #fff;
}
.btn-yellow {
  background: #ff9800;
  color: #fff;
}
.empty-tip {
  text-align: center;
  color: #bbb;
  font-size: 28rpx;
  margin-top: 80rpx;
}
.task-divider {
  height: 1px;
  background: #f0f0f0;
  margin: 0 -24rpx 18rpx -24rpx;
}
</style> 